<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工作流" prop="flowId">
        <el-select v-model="queryParams.flowId" filterable clearable placeholder="请选择工作流程">
          <el-option
            v-for="item in flowList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:document:add']"
        >发起新流程</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工作流" align="center" prop="flowName" />
      <el-table-column label="发起时间" align="center" prop="addTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="fileId">
        <template slot-scope="scope">
          <span v-html="getDownLink(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="当前步骤" align="center" prop="stepName" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="处理时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == '0' || scope.row.status == '4'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:document:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status == '0' || scope.row.status == '4' || scope.row.status == '8'"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleSend(scope.row)"
            v-hasPermi="['oa:document:add']"
          >发送</el-button>
          <el-button v-if="scope.row.status == '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleRollback(scope.row)"
            v-hasPermi="['oa:document:remove']"
          >撤销</el-button>
          <el-button v-if="scope.row.status != '0'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['oa:document:list']"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公文对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div class="block">
        <el-timeline>
        <el-timeline-item v-for="(p, index) in history"
         :timestamp="p.updateTime" placement="top">
          <el-card>
            <h4>{{p.comment}}</h4>
            <p>{{p.processUser}} {{statusFormat(p)}} 于 {{p.updateTime}}</p>
          </el-card>
        </el-timeline-item>
        </el-timeline>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="view">
        <el-form-item label="工作流" prop="flowId">
          <el-select v-model="form.flowId" filterable clearable placeholder="请选择工作流程" @change="loadField">
              <el-option
                v-for="item in flowList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
                size="small">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="f.field.title" v-for="f in form.form">
          <el-input v-model="f.content" :placeholder="'请输入'+f.field.title" v-if="f.field.type == '1'"/>
          <el-date-picker clearable size="small" style="width: 200px" v-if="f.field.type == '2'"
            v-model="f.content"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="'选择'+f.field.title">
          </el-date-picker>
          <el-input v-model="f.content" type="textarea" :placeholder="'请输入'+f.field.title" v-if="f.field.type == '3'"/>
          <el-input-number v-model="f.content" :placeholder="'请输入'+f.field.title" v-if="f.field.type == '4'"/>
        </el-form-item>
        <el-form-item label="附件" prop="fileId">
          <span v-html="getDownLink(form)" v-if="form.file != null"></span>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".doc, .docx, .pdf, .jpg, .jpeg, .png"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许上传文档或者图片文件！</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="发送" v-if="!view">
          <el-radio-group v-model="form.status">
            <el-radio label="0">稍后发送</el-radio>
            <el-radio label="1">立即发送</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { myDocument, getDocument, delDocument, rollbackDocument, addDocument, updateDocument, exportDocument, sendDocument } from "@/api/oa/document";
import { selectFlow} from "@/api/oa/flow";
import { selectField} from "@/api/oa/field";
import { listProcess} from "@/api/oa/process";
import { getToken } from "@/utils/auth";

export default {
  name: "Document",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作流数据
      flowList: [],
      // 字段数据
      fieldList: [],
      // 公文表格数据
      documentList: [],
      // 状态字典
      statusOptions: [],
      // 历史流程
      history:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        flowId: null,
        stepId: null,
        addTime: null,
        addUser: null,
        status: null
      },
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sys/files/upload"
      },
      // 日期范围
      dateRange: [],
      // 查看模式
      view: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        flowId: [
          { required: true, message: "工作流不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("flow_status").then(response => {
      this.statusOptions = response.data;
    });
    selectFlow().then(response => {
      this.flowList = response.rows;
    });
  },
  methods: {
    /** 查询公文列表 */
    getList() {
      this.loading = true;
      myDocument(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.documentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 加载字段 */
    loadField() {
      selectField({flowId:this.form.flowId, status:'1', sortName: 'list_sort', sortOrder: 'ASC'}).then(response => {
        this.form.form =[];
        for(var i=0;i<response.rows.length;i++){
          this.form.form.push({
            flowId:this.form.flowId,
            fieldId:response.rows[i]['id'],
            content:null,
            field: {'type':response.rows[i]['type'], code:response.rows[i]['code'], title:response.rows[i]['title']}
           });
        }
      });
    },
    //查询历史记录
    getHistory(row) {
      listProcess({documentId:row.id, sortName: 'pre_id', sortOrder: 'ASC'}).then(response => {
        this.history = response.rows;
        this.history.unshift({processUser:row.addUser, updateTime: row.addTime, status:'0'})
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 下载附件链接 */
    getDownLink(row) {
      if(row.file && row.file.id){
        return '<a href="'+process.env.VUE_APP_BASE_API+'/sys/files/download/'+row.file.id+'" target="_blank">'+row.file.title+'</a>';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        flowId: null,
        fileId: null,
        form: [],
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.view = false;
      this.title = "创建公文";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDocument(id).then(response => {
        this.form = response.data;
        //this.loadField();
        this.open = true;
        this.view = false;
        this.title = "修改公文";
      });
    },
    /** 发送按钮操作 */
    handleSend(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认发送选中的公文?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return sendDocument(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.getHistory(row);
      this.form.id = row.id;
      this.open = true;
      this.view = true;
      this.title = "查看流程";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDocument(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDocument(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 撤销按钮操作 */
    handleRollback(row) {
      this.$confirm('是否确认撤销选中的公文?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return rollbackDocument(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除选中的公文?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDocument(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.form.fileId = response.data.id
      this.form.file = response.data
      this.$refs.upload.clearFiles();
    }
  }
};
</script>
